package com.android.equipment.ui.device

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.annotation.RequiresApi
import com.android.equipment.R
import com.android.equipment.base.BaseActivity
import com.android.equipment.dao.Device
import com.android.equipment.dao.operate.DaoDevice
import com.android.equipment.dao.operate.DaoDeviceModel
import com.android.equipment.databinding.ActivityEditDeviceBinding
import com.android.equipment.utils.ToastUtil
import com.gyf.immersionbar.ImmersionBar
import com.hjq.bar.OnTitleBarListener
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.huawei.hms.hmsscankit.ScanUtil
import com.huawei.hms.ml.scan.HmsScan
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions
import com.luck.picture.lib.utils.DateUtils
import com.lxj.xpopup.XPopup

class EditDeviceActivity : BaseActivity<ActivityEditDeviceBinding>() {
    private val REQUEST_CODE_SCAN_ONE = 0X01
    lateinit var currentDevice: Device
    private var isEdit = false
    private var id: Long = 0
    override fun setLayoutContent(): ActivityEditDeviceBinding {
        return ActivityEditDeviceBinding.inflate(layoutInflater)
    }


    override fun initView(savedInstanceState: Bundle?) {
        id = intent.getLongExtra("id", 0L)
        isEdit = id > 0L
    }

    override fun initData() {
        if (isEdit) { // 修改
            binding.mTitleBar.setTitle("修改设备")
            binding.tvSubmit.text = "确认修改"
            val device = DaoDevice.getInstance().getDevice(id)
            currentDevice = device
            setDeviceInfo()
        } else { // 新增
            binding.mTitleBar.setTitle("新增设备")
            binding.tvSubmit.text = "确认新增"
            currentDevice = Device()
        }
    }

    private fun setDeviceInfo() {
        binding.etDeviceName.setText(currentDevice.deviceName)
        binding.etDeviceCode.setText(currentDevice.deviceCode)
        binding.tvDeviceModel.text = DaoDeviceModel.getInstance().getDeviceModel(currentDevice.deviceModelId).deviceModel
    }

    override fun initEvent() {
        super.initEvent()
        binding.mTitleBar.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(v: View?) {
                mSwipeBackHelper.backward()
            }

            override fun onTitleClick(v: View?) {
                TODO("Not yet implemented")
            }

            override fun onRightClick(v: View?) {
                TODO("Not yet implemented")
            }

        })

        binding.ivScan.setOnClickListener{
            XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.READ_MEDIA_IMAGES)
                .permission(Permission.READ_MEDIA_AUDIO)
                .permission(Permission.READ_MEDIA_VIDEO)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, allGranted: Boolean) {
                        if (!allGranted) {
                            //部分获取成功
                            XXPermissions.startPermissionActivity(mContext!!, permissions)
                            return
                        }


                        ScanUtil.startScan(
                            this@EditDeviceActivity,
                            REQUEST_CODE_SCAN_ONE,
                            HmsScanAnalyzerOptions.Creator().create()
                        )
                    }

                    override fun onDenied(permissions: List<String>, doNotAskAgain: Boolean) {
                        if (doNotAskAgain) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(mContext!!, permissions)
                        } else {
                            ToastUtil.showToastSafe("获取权限失败！")
                        }
                    }
                })
        }
        val builder = XPopup.Builder(this)
            .watchView(binding.tvDeviceModel)
        binding.tvDeviceModel.setOnClickListener{
            val deviceModelList = DaoDeviceModel.getInstance().notDelDeviceModel
            val stringList = deviceModelList.map { it.deviceModel }
            builder.asAttachList(stringList.toTypedArray(), null) { position, text ->
                binding.tvDeviceModel.text = text
                currentDevice.deviceModelId = deviceModelList[position].id
            }
                .show()

        }

        binding.tvSubmit.setOnClickListener{
            if (checkCurrentDevice()){
                if (isEdit){
                    currentDevice.updateTime = DateUtils.getYearDataFormat(System.currentTimeMillis())
                    DaoDevice.getInstance().updateDevice(currentDevice)
                    mSwipeBackHelper.backward()
                }else{
                    currentDevice.createTime = DateUtils.getYearDataFormat(System.currentTimeMillis())
                    DaoDevice.getInstance().addDevice(currentDevice)
                    mSwipeBackHelper.backward()
                }
            }
        }
    }

    private fun checkCurrentDevice(): Boolean{
        if (binding.etDeviceName.text.toString().isEmpty()){
            ToastUtil.showToastSafe("请输入设备名称")
            return false
        }

        if (binding.etDeviceCode.text.toString().isEmpty()){
            ToastUtil.showToastSafe("请输入或扫描设备编码")
            return false
        }

        if (binding.tvDeviceModel.text.toString().isEmpty()){
            ToastUtil.showToastSafe("请选择设备型号")
            return false
        }

        currentDevice.deviceName = binding.etDeviceName.text.toString()
        currentDevice.deviceCode = binding.etDeviceCode.text.toString()

        return true
    }

    override fun setStatusBar() {
        super.setStatusBar()
        ImmersionBar.with(this)
            .fullScreen(true)
            .statusBarColor(R.color.white)
            .statusBarDarkFont(true)
            .titleBar(binding.mTitleBar)
            .init()
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK || data == null) {
            return
        }
        if (requestCode == REQUEST_CODE_SCAN_ONE) {
            val obj: HmsScan? = data.getParcelableExtra(ScanUtil.RESULT)
            //val obj: HmsScan? = data.getParcelableExtra(ScanUtil.RESULT,HmsScan::class.java)
            if (obj != null) {
                val value: String = obj.originalValue
                binding.etDeviceCode.setText(value)
                currentDevice.deviceCode = value
            }
        }
    }
}
